<template>
  <a-tabs default-active-key="1">
    <a-tab-pane class="home">
      <span slot="tab">
        <a-icon type="home" theme="filled" />
      </span>
    </a-tab-pane>
    <a-tab-pane key="1">
      <a-dropdown :trigger="['contextmenu']" slot="tab">
        <div>人员列表<a-icon type="close" class="close" /></div>
        <a-menu slot="overlay">
          <a-menu-item key="1">
            关闭页签
          </a-menu-item>
          <a-menu-item key="2">
            关闭右侧页签
          </a-menu-item>
          <a-menu-item key="3">
            关闭全部页签
          </a-menu-item>
        </a-menu>
      </a-dropdown>
    </a-tab-pane>
    <a-tab-pane key="2">
      <span slot="tab">组织管理<a-icon type="close" class="close" /> </span>
    </a-tab-pane>
    <a-tab-pane key="3">
      <span slot="tab">角色管理<a-icon type="close" class="close" /> </span>
    </a-tab-pane>
    <a-tab-pane v-for="index of 20" :key="`tab${index}`">
      <span slot="tab">角色管理{{ index }}<a-icon type="close" class="close" /> </span>
    </a-tab-pane>
  </a-tabs>
</template>

<script>
import events from "./events";
import { getParentByTag } from "@/utils/util";

export default {
  name: "MultiTab",

  data() {
    return {
      activeKey: "", //当前激活标签页
      menus: [
        {
          fdId: "1",
          i18n: {
            name: {
              "zh-CN": "人员管理",
            },
          },
        },
        {
          fdId: "2",
          i18n: {
            name: {
              "zh-CN": "行政组织",
            },
          },
        },
        {
          fdId: "3",
          i18n: {
            name: {
              "zh-CN": "角色",
            },
          },
        },
        {
          fdId: "4",
          i18n: {
            name: {
              "zh-CN": "岗位",
            },
          },
        },
      ],
    };
  },

  computed: {},

  watch: {
    activeKey: function(newPathKey) {
      this.$router.push({ path: newPathKey });
    },
  },

  created() {
    // bind event
    events
      .$on("open", val => {
        if (!val) {
          throw new Error(`multi-tab: open tab ${val} err`);
        }
        this.activeKey = val;
      })
      .$on("close", val => this.closeThat(val ? val : this.activeKey));

    // 当前访问路径不在当前tab数组中并且路径属于当前子应用，将当前访问路由对象添加到tab数组中
    /* if (!this.fullPaths.includes(this.$route.fullPath) && this.nowAppKey === this.$route.fullPath.split("/")[1]) {
      this.pages = [...this.pages, this.$route];
    }
    if (!this.appPages[this.nowAppKey]) {
      this.toLast();
    } else {
      this.activeKey = this.appPages[this.nowAppKey];
    } */
  },

  methods: {
    //跳转至当前应用首页
    toHome() {
      this.$router.push({
        path: `/${this.nowAppKey}/indexPage`,
      });
    },

    //跳转至最后一个标签页
    toLast() {
      this.activeKey = this.fullPaths[this.fullPaths.length - 1];
    },

    /**
     * @description: 新增和删除页签的回调
     * @param {String} targetKey 操作页签的路由
     * @param {String} action 操作类型 remove
     */
    onEdit(targetKey, action) {
      this[action](targetKey);
    },

    /**
     * @description: 删除页签
     * @param {String} targetKey 页签的key, fullPath
     */
    remove(targetKey) {
      // 清空 keep-alive 缓存
      const component = this.$route.matched.find(el => el.path === this.$route.path).instances.default;
      let node = component.$vnode;
      // 获取到tag中包含keep-alive字符串的节点
      node = getParentByTag(node, "keep-alive");
      let cache = node.componentInstance.cache;
      let keys = node.componentInstance.keys;
      setTimeout(() => {
        if (cache[targetKey]) {
          if (keys.length) {
            const index = keys.indexOf(targetKey);
            if (index !== -1) keys.splice(index, 1);
          }
          delete cache[targetKey];
        }
      }, 100);

      // 销毁删除路由对应组件
      if (this.instances && this.instances[targetKey]) {
        this.instances[targetKey].$destroy();
        delete this.instances[targetKey];
      }

      // 跳转路由
      this.pages = this.pages.filter(page => page.fullPath !== targetKey);
      if (this.pages.length) {
        // 判断当前标签是否关闭，若关闭则跳转到最后一个还存在的标签页
        if (!this.fullPaths.includes(this.activeKey)) {
          this.toLast();
        }
      } else {
        // 判断是否关闭的最后一个页签，若是则跳转到首页
        this.toHome();
      }
    },

    // 右键：关闭当前
    closeThat(e) {
      this.remove(e);
    },

    // 右键：关闭其他
    closeOther(e) {
      const currentIndex = this.fullPaths.indexOf(e);
      this.fullPaths.forEach((item, index) => {
        if (index !== currentIndex) {
          this.remove(item);
        }
      });
    },

    // 右键：关闭左侧
    closeLeft(e) {
      const currentIndex = this.fullPaths.indexOf(e);
      if (currentIndex > 0) {
        this.fullPaths.forEach((item, index) => {
          if (index < currentIndex) {
            this.remove(item);
          }
        });
      } else {
        this.$message.info("左侧没有标签");
      }
    },

    // 右键：关闭右侧
    closeRight(e) {
      const currentIndex = this.fullPaths.indexOf(e);
      if (currentIndex < this.fullPaths.length - 1) {
        this.fullPaths.forEach((item, index) => {
          if (index > currentIndex) {
            this.remove(item);
          }
        });
      } else {
        this.$message.info("右侧没有标签");
      }
    },

    // 右键：关闭全部
    closeAll(e) {
      this.fullPaths
        .filter(path => path.indexOf("/indexPage") === -1)
        .forEach((item, index) => {
          this.remove(item);
        });
    },

    //渲染Tab标签项的右键下拉菜单
    renderTabPaneMenu(keyPath) {
      // 关闭当前标签、关闭其他、关闭右侧、关闭左侧、关闭全部
      return (
        <a-menu
          {...{
            on: {
              click: ({ key, item, domEvent }) => this[key](keyPath),
            },
          }}
        >
          <a-menu-item key="closeThat">关闭当前</a-menu-item>
          <a-menu-item key="closeOther">关闭其他</a-menu-item>
          <a-menu-item key="closeRight">关闭右侧</a-menu-item>
          <a-menu-item key="closeLeft">关闭左侧</a-menu-item>
          <a-menu-item key="closeAll">关闭所有</a-menu-item>
        </a-menu>
      );
    },

    //渲染带右键菜单的Tab标签项
    renderTabPane(title, keyPath) {
      const menu = this.renderTabPaneMenu(keyPath);
      return (
        <a-dropdown overlay={menu} trigger={["contextmenu"]}>
          <span style={{ userSelect: "none" }}>{title}</span>
        </a-dropdown>
      );
    },
  },

  // render() {
  //   const { onEdit } = this;
  //   const panes = [<a-tab-pane style={{ height: 0 }} tab="tab1" key="tab1"></a-tab-pane>, <a-tab-pane style={{ height: 0 }} tab="tab2" key="tab2"></a-tab-pane>];

  //   return (
  //     // 判断移动端时没有左侧菜单栏 宽度显示100%
  //     <div class="ant-pro-multi-tab">
  //       <div class="homw-icon-wrap">
  //         <a-icon onClick={() => this.toHome()} style={{ color: this.$route.path === `/${this.nowAppKey}/indexPage` ? "#00aaa6" : "#BFBFBF" }} theme="filled" type="home" />
  //       </div>
  //       <div style="flex:1; overflow: hidden" class="ant-pro-multi-tab-wrapper">
  //         {panes && panes.length ? (
  //           <a-tabs hideAdd type={"editable-card"} v-model={this.activeKey} tabBarStyle={{ background: "#FFF", margin: 0, paddingLeft: "16px", paddingTop: "1px" }} {...{ on: { edit: onEdit } }}>
  //             {panes}
  //           </a-tabs>
  //         ) : null}
  //       </div>
  //     </div>
  //   );
  // },
};
</script>
